package cn.jolyoulu.common.web.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: JolyouLu
 * @Date: 2023/1/21 16:17
 * @Description 过滤器
 */
public class MultiReadHttpServletFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //包装为可重复读的HttpServletRequest
        MultiReadHttpServletRequestWrapper requestWrapper = new MultiReadHttpServletRequestWrapper((HttpServletRequest) servletRequest);
        //包装为可重复读的HttpServletResponse
        MultiReadHttpServletResponseWrapper responseWrapper = new MultiReadHttpServletResponseWrapper((HttpServletResponse) servletResponse);
        try {
            //执行后续的过滤器
            filterChain.doFilter(requestWrapper, responseWrapper);
        }finally {
            //获取响应数据
            byte[] respBytes = responseWrapper.toByteArray();
            if (respBytes.length > 0){
                //这里才是真正的写数据,往原始的HttpResponse对象中写入数据
                responseWrapper.setContentLength(respBytes.length);
                try(OutputStream out = servletResponse.getOutputStream()){
                    out.write(respBytes);
                    out.flush();
                }
            }
        }
    }
}
